package com.le.tester.imooc.masterJUC.lock.deadlock;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;

/**
 * 描述：用threadMXBean检测死锁
 */
public class ThreadMXBeanDetection implements Runnable {
    private int flag = 1;

    static final Object o1 = new Object();
    static final Object o2 = new Object();

    public static void main(String[] args) throws InterruptedException {
        ThreadMXBeanDetection mustDeadLock0 = new ThreadMXBeanDetection();
        ThreadMXBeanDetection mustDeadLock1 = new ThreadMXBeanDetection();
        mustDeadLock0.flag = 0;
        mustDeadLock1.flag = 1;

        new Thread(mustDeadLock0).start();
        new Thread(mustDeadLock1).start();

        Thread.sleep(1000);

        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        //获取死锁的线程的id
        long[] deadlockedThreads = threadMXBean.findDeadlockedThreads();
        int length = deadlockedThreads.length;

        if (length > 0) {
            for (long deadlockedThread : deadlockedThreads) {
                ThreadInfo threadInfo = threadMXBean.getThreadInfo(deadlockedThread);
                System.out.println("发现了死锁：" + threadInfo.getThreadName());

            }
        }

    }

    @Override
    public void run() {
        System.out.println("flag=" + flag);
        if (flag == 1) {
            synchronized (o1) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("线程1锁住了o1");
                }
            }

        }
        if (flag == 0) {
            synchronized (o2) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1) {
                    System.out.println("线程2锁住了o2");
                }
            }
        }
    }
}
